"""
Django管理命令：自动同步权限
用法：python manage.py sync_permissions
"""
from django.core.management.base import BaseCommand
from rbac.auto_permissions import sync_permissions, get_permission_report


class Command(BaseCommand):
    help = '自动扫描视图函数并同步权限'

    def add_arguments(self, parser):
        parser.add_argument(
            '--report-only',
            action='store_true',
            help='仅显示权限状态报告，不进行同步',
        )
        parser.add_argument(
            '--verbose',
            action='store_true',
            help='显示详细信息',
        )

    def handle(self, *args, **options):
        self.stdout.write(
            self.style.SUCCESS('🔍 权限自动同步工具')
        )
        
        if options['report_only']:
            # 仅显示报告
            self.stdout.write(
                self.style.WARNING('📊 生成权限状态报告...')
            )
            report = get_permission_report()
            
            self.stdout.write(
                self.style.SUCCESS(
                    f'📈 权限状态统计:'
                    f'\n   - 发现视图函数: {report["total_views"]} 个'
                    f'\n   - 已有权限标记: {report["views_with_permissions"]} 个'
                    f'\n   - 未标记权限: {report["views_without_permissions"]} 个'
                )
            )
            
            if options['verbose']:
                self.stdout.write(
                    self.style.WARNING('\n📁 按模块分组:')
                )
                for module, views in report['by_module'].items():
                    self.stdout.write(f'   📦 {module}:')
                    for view in views:
                        status = '✅' if view['has_permission'] else '❌'
                        self.stdout.write(f'      {status} {view["name"]}')
        else:
            # 执行同步
            self.stdout.write(
                self.style.WARNING('🚀 开始自动权限同步...')
            )
            
            try:
                result = sync_permissions()
                
                self.stdout.write(
                    self.style.SUCCESS(
                        f'🎉 权限同步完成!'
                        f'\n   - 发现视图: {result["total_discovered"]} 个'
                        f'\n   - 新创建权限: {len(result["created"])} 个'
                        f'\n   - 更新权限: {len(result["updated"])} 个'
                    )
                )
                
                if result['created']:
                    self.stdout.write(
                        self.style.SUCCESS('📝 新创建的权限:')
                    )
                    for perm in result['created']:
                        self.stdout.write(f'   ✨ {perm.name} ({perm.code})')
                
                self.stdout.write(
                    self.style.SUCCESS(
                        '\n💡 接下来您可以:'
                        '\n   1. 访问 /rbac/permissions/ 查看权限列表'
                        '\n   2. 访问 /rbac/roles/ 管理角色权限'
                        '\n   3. 使用 @require_permission 装饰器标记新视图'
                    )
                )
                
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'❌ 同步失败: {str(e)}')
                )
                if options['verbose']:
                    import traceback
                    self.stdout.write(traceback.format_exc())
                raise e
        
        self.stdout.write(
            self.style.SUCCESS('✨ 操作完成')
        )